import React from 'react'
import { connect } from 'react-redux'
import { validForm as validFormDuck } from 'ducks'
import {
  Form, Input, Label, Icon, TextArea,
} from 'semantic-ui-react'
import PropTypes from 'prop-types'
import Styled from 'styled-components'

const switchIcon = (state, defaultIcon) => {
  let name = defaultIcon
  if (state === 'success') {
    name = 'checkmark'
  } else if (state === 'error') {
    name = 'remove'
  } else if (state === 'warning') {
    name = 'warning sign'
  }
  return name
}
const switchIconColor = {
  success: 'teal',
  error: 'red',
  warning: 'orange',
}

const ValidFormInput = ({
  name,
  value,
  state,
  rules,
  errorMessage,
  labelString,
  actionFieldChange,
  icon,
  fluid,
  textAlign,
  textArea,
  ...otherProps
}) => (
  <Form.Field error={state === 'error'} style={{ textAlign: 'left' }}>
    {labelString && <label>labelString</label>}
    {textArea && (
      <TextArea
        onChange={(e, d) => actionFieldChange(d.name, d.value, d.rules)}
        name={name}
        value={value}
        rules={rules}
        style={{ maxWidth: '500px' }}
        {...otherProps}
      />
    )}
    {!textArea && (
      <Input
        loading={state === 'loading'}
        fluid={fluid}
        icon={<Icon name={switchIcon(state, icon)} color={switchIconColor[state]} />}
        onChange={(e, d) => actionFieldChange(d.name, d.value, d.rules)}
        name={name}
        value={value}
        rules={rules}
        {...otherProps}
      />
    )}
    {state === 'error' && (
      <Label
        basic
        pointing={fluid ? true : 'left'}
        style={{
          backgroundColor: '#fff',
          borderColor: '#db2828',
          color: '#db2828',
        }}
      >
        {errorMessage}
      </Label>
    )}
  </Form.Field>
)

ValidFormInput.propTypes = {
  actionFieldChange: PropTypes.func.isRequired,
  otherProps: PropTypes.object.isRequired,
  value: PropTypes.string.isRequired,
  state: PropTypes.string.isRequired,
  rules: PropTypes.array.isRequired,
  labelString: PropTypes.string.isRequired,
  errorMessage: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  valid: PropTypes.bool,
  icon: PropTypes.string.isRequired,
}

ValidFormInput.defaultProps = {
  valid: false,
}

const mapStateToProps = (state, ownProps) => ({
  value: validFormDuck.selectors.fieldValue(state, ownProps.name),
  state: validFormDuck.selectors.fieldState(state, ownProps.name),
  errorMessage: validFormDuck.selectors.fieldErrorMessage(state, ownProps.name),
  focusField: validFormDuck.selectors.focusField(state),
})

const mapDispatchToProps = {
  actionFieldChange: validFormDuck.creators.actionFieldChange,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(ValidFormInput)
